package com.linux.huhx.business.action;

import com.linux.huhx.base.BaseController;
import com.linux.huhx.business.service.RegisterService;
import com.linux.huhx.constants.Constants;
import com.linux.huhx.constants.ConstantsMsg;
import com.linux.huhx.utils.EncryptUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 注册的处理类
 *
 * @author huhx
 * @date: 2016年12月18日 上午11:55:55
 */
public class RegisterAction extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(RegisterAction.class);

    private RegisterService registerService;

    public void setRegisterService(RegisterService registerService) {
        this.registerService = registerService;
    }

    @Override
    protected Map handleInner(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 得到数据
        String email = (String) request.getAttribute("Email");
        String username = (String) request.getAttribute("Username");
        String password = (String) request.getAttribute("Password");

        // 用户的邮箱不能为空
        if (StringUtils.isEmpty(email)) {
            return null;
        }

        // 用户的名字不能为空
        if (StringUtils.isEmpty(username)) {
            return null;
        }
        // 用户的密码不能为空
        if (StringUtils.isEmpty(password)) {
            return null;
        }

        // 对密码加密
        String encryptPassword = EncryptUtils.md5Encrypt(password);
        logger.info("email: " + email + ", password: " + encryptPassword);

        // 校验邮箱是否存在
        Long userId = registerService.queryUserIdByEmail(email);
        if (!StringUtils.isEmpty(userId)) {
            return null;
        }

        // 保存用户的数据
        Map<String, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("userType", Constants.USER_TYPE_NORMAL); // 只能是普通用户
        userInfoMap.put("userStatus", Constants.USER_STATUS_NORMAL); // 正常用户
        userInfoMap.put("email", email);
        userInfoMap.put("username", username);
        userInfoMap.put("password", encryptPassword);
        registerService.saveUserInfo(userInfoMap);

        // 返回数据
        return null;
    }
}
